package top.ochiamalu.aioj.service.impl;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import top.ochiamalu.aioj.properties.AIOJProperties;
import top.ochiamalu.aioj.service.FileService;
import top.ochiamalu.aioj.util.FileUtils;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;

import static top.ochiamalu.aioj.constant.SystemConstants.DEFAULT_BUFFER_SIZE;
import static top.ochiamalu.aioj.constant.SystemConstants.FILE_END;

/**
 * 文件上传服务impl
 *
 * @author ochiamalu
 * @date 2025/02/10
 */
@Service
public class FileServiceImpl implements FileService {

    @Resource
    private AIOJProperties aiojProperties;

    @Value("${ai-oj.qiniu.url:null}")
    private String qiniuUrl;

    @Value("${server.servlet.session.cookie.domain}")
    private String host;

    @Value("${server.port}")
    private String port;

    @Override
    public String uploadImage(MultipartFile file) {
        if (aiojProperties.isUseLocalStorage()) {
            String fileName = FileUtils.uploadFile2Local(file);
            return "http://" + host + ":" + port + "/api/files/" + fileName;
        } else {
            String fileName = FileUtils.uploadFile2Cloud(file);
            return qiniuUrl + fileName;
        }
    }

    @Override
    public void downloadFile(String name, HttpServletResponse response) {
        try {
            //获取指定文件
            File img = new File(System.getProperty("user.dir") + aiojProperties.getImg() + name);
            //获取输入流
            FileInputStream inputStream = new FileInputStream(img);
            //获取输出流
            ServletOutputStream outputStream = response.getOutputStream();
            //指定response类型
            response.setContentType("image/jpeg");
            int len = 0;
            //设置缓冲区大小
            byte[] bytes = new byte[DEFAULT_BUFFER_SIZE];
            //将文件从输入流读到缓冲区，输出流读取缓冲区内容
            while ((len = inputStream.read(bytes)) != FILE_END) {
                outputStream.write(bytes, 0, len);
                outputStream.flush();
            }
            inputStream.close();
            outputStream.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
